import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    allkeylist: [],
    keyList: [],
    zuijList: JSON.parse(localStorage.getItem('zjlist')) || [],
  },
  mutations: {
    ALLKEWYLIST(state, item) {
      state.allkeylist = item
    },
    KEYLIST(state, key) {
      state.keyList = [],
        state.allkeylist.map((ele) => {
          if (ele.productName.includes(key)) {
            console.log(ele);
            state.keyList.push(ele)
          }
        })
      localStorage.setItem('gjzList', JSON.stringify(state.keyList))
    },
    ZUIJINLIST(state, item) {
      // 查找最近搜索数组中有没有
      var index = state.zuijList.findIndex((ele) => {
        // input的值和数组中的值比较 然后返回下标 再拿下标判断
        return ele === item
      })
      // 不等于-1 就是有 有就删除
      if (index != -1) {
        state.zuijList.splice(index, 1)
      }
      // 删除后在添加到前面
      state.zuijList.unshift(item);
      // 这个数组到6长度
      if (state.zuijList.length > 6) {
        // 把数组最后一个删除
        state.zuijList.pop()
      }
      localStorage.setItem('zjlist', JSON.stringify(state.zuijList))
    },
    SEADRCH() {

    },
    // 删除
    DELE(state,index){
      state.zuijList.splice(index,1)
      localStorage.setItem('zjlist', JSON.stringify(state.zuijList))
    }
  },
  actions: {
    ALLKEWYLIST(context) {
      axios.get("./data.json").then((res) => {
        console.log(res.data.result.list);
        context.commit('ALLKEWYLIST', res.data.result.list)
      }).catch((err) => {
        console.log(err);
      })
    },
    KEYLIST(context, key) {
      context.commit('KEYLIST', key)
    },
    ZUIJINLIST(context, item) {
      context.commit('ZUIJINLIST', item)
    },
    SEADRCH(context, item) {
      context.commit('SEADRCH', item)
    },
    // 删除
    DELE(context,index){
      context.commit('DELE', index)
    }
  },
  modules: {
  }
})
